//------------------------------------------------------------//
//  FileDownloader.java:                                      //
//------------------------------------------------------------//
//  A Java program that can be used to download the contents  //
//  of a specified URL.                                       //
//------------------------------------------------------------//
//  Code created by Developer's Daily                         //
//  http://www.codevoter.net                                  //
//------------------------------------------------------------//

package net.codevoter.url;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 
 * @author codevoter.net
 *
 */
public class FileDownloader {
	
	public void download(String urlString) {
		try {
			//initial input stream
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
			
			//Get output stream
			File outFile = new File("c:/test.zip");
			if(!outFile.exists())
				outFile.createNewFile();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
			
			//read and write the data
			byte[] buffer = new byte[4096];
			int count = -1;
			while ((count = bis.read(buffer)) != -1) {
				bos.write(buffer,0,count);
			}
			
			bos.flush();
			bos.close();
			bis.close();
		} catch (MalformedURLException e) {
			System.out.println("can not connect to" + urlString);
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			System.out.println("file path is not valid.");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		FileDownloader client = new FileDownloader();
//		client.download("http://59.duote.com.cn/foxitpdf.zip");
		try {
			URL url = new URL("http://www.baidu.com");
			URI uri = url.toURI();
			System.out.println(uri.getAuthority());
			System.out.println(uri.getFragment());
			System.out.println(uri.getPath());
			System.out.println(uri.getRawPath());
			System.out.println(uri.getSchemeSpecificPart());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
